package com.chen.base.module.login.service.impl;

import com.chen.base.handler.Tokener;
import com.chen.base.module.base.dto.Response;
import com.chen.base.module.base.service.impl.BaseServiceImpl;
import com.chen.base.module.login.contract.dto.AdminLoginDTO;
import com.chen.base.module.login.contract.vo.AdminLoginVO;
import com.chen.base.module.login.service.AdminService;
import com.chen.dao.base.login.AdminRepository;
import com.chen.entity.base.login.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Title: manager-spring-mvc-hb
 * @Description: to do
 * @Author: chenjiwei
 * @Date: 2020-11-17 22:33
 * @Version: 1.0.0
 */
@Service
public class AdminServiceImpl extends BaseServiceImpl<Admin> implements AdminService<Admin> {

    @Autowired
    private AdminRepository adminRepository;

    @Override
    public Response login(AdminLoginVO vo) {
        try{
            Admin admin = adminRepository.findByUsername(vo.getUsername());
            if(null == admin)
                return Response.fail("账户不存在");

            if("01".equals(admin.getState()))
                return Response.fail("账户状态未启用");

            if(admin.getLoginCount() >=5)
                return Response.fail("输入密码错误超过5次，已锁定");

            if(!admin.getPassword().equals(vo.getPassword())){
                admin.setLoginCount(admin.getLoginCount()+1);
                admin.setUpdateTime(new Date());
                adminRepository.save(admin);
                return Response.fail("密码错误");
            }
            admin.setLoginCount(0);
            admin.setUpdateTime(new Date());
            adminRepository.save(admin);

            AdminLoginDTO adminLoginDTO = new AdminLoginDTO();
            adminLoginDTO.setToken(Tokener.createJWT("subj", admin, 6*60*60*1000));
            return Response.success("登录成功", adminLoginDTO);
        }catch (Exception e){
            e.printStackTrace();
            return Response.fail("登录异常："+e.getMessage());
        }
    }

    @Override
    public JpaSpecificationExecutor<Admin> getBaseRepository() {
        return adminRepository;
    }

    @Override
    protected String filterForFindAll() {
        return null;
    }
}
